package com.bw.exam.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.exam.pojo.Specification;
import com.bw.exam.pojo.SpecificationOption;
import com.bw.exam.service.SpecificationOptionService;
import com.bw.exam.service.SpecificationService;
import com.bw.exam.mapper.SpecificationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author liuzhiping
* @description 针对表【tb_specification】的数据库操作Service实现
* @createDate 2024-08-15 11:26:34
*/
@Service
@Slf4j
public class SpecificationServiceImpl extends ServiceImpl<SpecificationMapper, Specification>
    implements SpecificationService{

    @Autowired
    private SpecificationOptionService specificationOptionService;

    @Transactional
    @Override
    public boolean add(Specification specification) {
        //添加主表
        this.save(specification);

        for (SpecificationOption specificationOption : specification.getSpecificationOptionList()) {
            specificationOption.setSpecId(specification.getId());
        }
        //添加副表
        this.specificationOptionService.saveBatch(specification.getSpecificationOptionList());

        return true;
    }

    @Transactional
    @Override
    public boolean update(Specification specification) {

        log.info("修改规格 specification:{}", JSON.toJSONString(specification));

        //修改主表
        this.updateById(specification);


        LambdaQueryWrapper<SpecificationOption> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SpecificationOption::getSpecId,specification.getId());
        //删除副表
        this.specificationOptionService.remove(lambdaQueryWrapper);

        //插入副表
        for (SpecificationOption specificationOption : specification.getSpecificationOptionList()) {
            specificationOption.setSpecId(specification.getId());
        }
        //添加副表
        this.specificationOptionService.saveBatch(specification.getSpecificationOptionList());
        return true;
    }

    @Transactional
    @Override
    public boolean del(Long id) {

        //删除副表
        LambdaQueryWrapper<SpecificationOption> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SpecificationOption::getSpecId,id);
        this.specificationOptionService.remove(lambdaQueryWrapper);

        //删除主表
        this.removeById(id);
        return true;
    }
}




